﻿using Framework.Core;
using Framework.WebApi.Authentication;
using Framework.WebApi.Authorization;
using Microsoft.AspNetCore.Authorization;

namespace Framework.WebApi.Test
{
	public class JwtHandler : AppAuthorizeHandler
	{
		/// <summary>
		/// 自动刷新Token
		/// </summary>
		/// <param name="context"></param>
		/// <param name="httpContext"></param>
		/// <returns></returns>
		public override async Task HandleAsync(AuthorizationHandlerContext context)
		{
			// todo:真正使用需要从配置文件获取
			var tokenExpire = 30;
			var refreshTokenExpire = 30;
			if (JWTEncryption.AutoRefreshToken(context, context.GetCurrentHttpContext(), tokenExpire, refreshTokenExpire))
			{
				await AuthorizeHandleAsync(context);
			}
			else
			{
				context.Fail(); // 授权失败
				var currentHttpContext = context.GetCurrentHttpContext();
				if (currentHttpContext == null) return;
			}
		}

		/// <summary>
		/// 策略验证管道
		/// </summary>
		/// <param name="context"></param>
		/// <param name="httpContext"></param>
		/// <param name="requirement"></param>
		/// <returns></returns>
		public override async Task<bool> PolicyPipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext, IAuthorizationRequirement requirement)
		{
			return await Task.FromResult(true);
		}

		public override async Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
		{
			// 已自动验证 Jwt Token 有效性
			return await CheckAuthorizeAsync(httpContext);
		}

		/// <summary>
		/// 权限校验核心逻辑
		/// </summary>
		/// <param name="httpContext"></param>
		/// <returns></returns>
		private static async Task<bool> CheckAuthorizeAsync(DefaultHttpContext httpContext)
		{
			// 路由名称
			var routeName = httpContext.Request.Path.StartsWithSegments("/api")
				? httpContext.Request.Path.Value![5..].Replace("/", ":")
				: httpContext.Request.Path.Value![1..].Replace("/", ":");

			// todo:真正使用需要从数据库中获取权限进行校验判断

			return true;
		}
	}
}
